<template>
  <div class="post">
    <h1 style="font-weight: 900">{{ form.title }}</h1>
    <div
      style="
          position: absolute;
          width: 70%;
          background-color: #fff;
          height: 60px;
          border-radius: 10px;
          /*padding: 10px;*/
          display: flex;
          flex-wrap: nowrap;
        "
    >
      <div>
          <span>
            <a-image
              :width="40"
              src="https://csdnimg.cn/release/blogv2/dist/pc/img/original.png"
            />
          </span>
      </div>
      <div style="width: 100%;padding: 10px">
        <div
          style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
        >
            <span style="display: flex; gap: 20px; color: #999aaa">
                <span style="color: #555666;font-size: 14px">{{ form.user.userName }}</span>
              <span style="font-size: 12px; gap: 10px">
                <ClockCircleOutlined />
                于{{ formatDateTime(form.createTime) }}发布
              </span>
              <Favour :post-id="form.id"></Favour>
            </span>
          <span>
              <span v-if="isEdit">
                <a-button type="link" primary size="small" @click="gotoEdit"
                >编辑</a-button
                >|
                <a-button type="link" danger size="small" @click="delModal"
                >删除</a-button
                >
              </span>
            </span>
        </div>

        <div style="color: #999aaa; font-size: 12px; gap: 12px">
          <span>文章标签: &nbsp;&nbsp;</span>
          <span>
              <a-tag v-for="i in form.tagList" :key="i" color="default">
                {{ i }}
              </a-tag>
            </span>
        </div>
      </div>
    </div>
    <v-md-preview :text="form.content"></v-md-preview>
  </div>
</template>

<script setup lang="ts">
import { createVNode, onBeforeMount, ref } from "vue";
import myAxios from "@/plugins/myAxios";
import { useRoute } from "vue-router";
import { message, Modal } from "ant-design-vue";
import {
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  LikeOutlined,
  StarOutlined,
} from "@ant-design/icons-vue";
import router from "@/router";
import Favour from "@/components/Favour/Favour.vue";

const route = useRoute();

function formatDateTime(date: string): string {
  const datetime = new Date(date);
  const year = datetime.getFullYear();
  const month = String(datetime.getMonth() + 1).padStart(2, "0");
  const day = String(datetime.getDate()).padStart(2, "0");
  const hour = String(datetime.getHours()).padStart(2, "0");
  const minute = String(datetime.getMinutes()).padStart(2, "0");
  const format = `${year}-${month}-${day} ${hour}:${minute}`;
  return format;
}

let user = ref({
  id: "",
  userName: "",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  createTime: "",
  updateTime: "",
});
const getLoginUser = async () => {
  await myAxios.get("user/get/login").then((res: any) => {
    if (res !== null) {
      user.value = res;
      localStorage.setItem("isLogin", "true");
      localStorage.setItem("id", res.id);
      localStorage.setItem("userRole", res.userRole);
      isLogin = true;
      // console.log(localStorage);
    } else {
      user.value.id = "";
      localStorage.removeItem("isLogin");
      localStorage.removeItem("id");
      localStorage.removeItem("userRole");
    }
  });
};

let form = ref({
  id: "",
  title: "由于对象流解析的数据与流的头部信息不匹配导致异常",
  content: "今天在做韩顺平老师的多人在线通讯系统，",
  thumbNum: 0,
  favourNum: 0,
  userId: "1651162509424558081",
  createTime: "2023-04-26T14:15:34.000+00:00",
  updateTime: "2023-04-26T14:27:35.000+00:00",
  tagList: [],
  user: {
    id: "1651162509424558081",
    userName: "kkkkkba",
    userAvatar:
      "https://pica.zhimg.com/80/v2-6606555d10fd91e4b9b581f841fab966_720w.webp?source=1940ef5c",
    userProfile: "再打扰就不礼貌了",
    userRole: "admin",
    createTime: "2023-04-26T09:53:14.000+00:00",
  },
  hasThumb: false,
  hasFavour: false,
});

let favourMessage = ref({
  thumbNum: 1000,
  favourNum: 99999,
  hasThumb: false,
  hasFavour: false,
});
const gotoEdit = () => {
  router.push(`/edit/post/${form.value.id}`);
};
const delModal = () => {
  Modal.confirm({
    content: "确定要删除此文章吗？删除后不可恢复",
    icon: createVNode(ExclamationCircleOutlined),
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 500);
      }).catch(() => delPost());
    },
    cancelText: "取消",
    onCancel() {
      Modal.destroyAll();
    },
  });
};

const delPost = () => {
  const Params = {
    id: route.params.category,
  };
  myAxios.post(`/post/delete`, Params).then((res: any) => {
    if (res == true) {
      message.success("文章删除成功");
      router.push(`/deleteSuccess/${form.value.id}`);
    } else {
      message.error("系统错误");
    }
  });
};
let isEdit = false;
let isLogin = false;
const getPostById = async () => {
  const id = route.params.category;
  await myAxios.get(`post/get/vo?id=${id}`).then((res: any) => {
    if (res !== null) {
      form.value = res;
      document.title = form.value.title;
      isEdit =
        form.value.user.id === localStorage.getItem("id") ||
        localStorage.getItem("userRole") === "admin";
      favourMessage.value = form.value;
    } else {
      form.value = res;
      router.push("/404");
    }
  });
};
onBeforeMount(() => {
  getLoginUser();
  getPostById();
});

const actions: Record<string, any>[] = [
  { icon: StarOutlined, text: "156" },
  { icon: LikeOutlined, text: "156" },
];
</script>

<style scoped>
.post {
  margin-top: 10px;
  padding: 5px;
  /*background-color: #c72f2f;*/
}
</style>
